package cn.zsb.web;

import cn.zsb.entity.Page;
import cn.zsb.entity.Result;
import cn.zsb.entity.User;
import cn.zsb.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * wen
 *
 * @author oldliu
 * @since 1.0
 */
@RestController
@RequestMapping("user")
public class UserController {

    @Value("${server.port}")
    int port;
    @Autowired
    private UserService userService;
    //private UserService userService=SpringUtil.getBean(UserService.class);


    @GetMapping("page")
    public ModelAndView page(@RequestParam(required = false) String sname,
                             @RequestParam(required = false) String phone,
                             @RequestParam(name = "page", defaultValue= "1") int pageNo,
                             @RequestParam(name = "limit", defaultValue = "10") int pageSize,
                             @RequestParam(name = "start", required = false) Date start,
                             @RequestParam(name = "end", required = false) Date end
                             ) {
        ModelAndView mv = new ModelAndView();
        mv.addObject("sname",sname);
        mv.addObject("phone",phone);
        mv.addObject("start",start);
        mv.addObject("end",end);
        mv.addObject("p", this.userService.page(sname, phone,start,end, pageNo, pageSize));
        mv.setViewName("users");
        return mv;
    }
    @GetMapping("pageAjax")
    public Page<User> pageAjax(@RequestParam(required = false) String sname,
                             @RequestParam(required = false) String phone,
                             @RequestParam(name = "page", defaultValue= "1") int pageNo,
                             @RequestParam(name = "limit", defaultValue = "10") int pageSize,
                             @RequestParam(name = "start", required = false) Date start,
                             @RequestParam(name = "end", required = false) Date end
    ) {
        System.out.println("当前数据从"+this.port+"端口获得！");
        Page<User> page = this.userService.page(sname, phone, start, end, pageNo, pageSize);
        return page;
    }
//    @PostMapping("add")
//    public String add(@RequestBody User user) throws IOException {
//        //getParameter payload  a=2&b=20&c=100
//        //{},HttpServletRequest request
////        BufferedReader br=new BufferedReader(new InputStreamReader(request.getInputStream()));
////        String line="",str=null;
////        while ((str=br.readLine())!=null){
////            line+=str;
////        }
////        System.out.println(line+">>>>>>>>>>>>>>>>>>>>>>>");
//
//        System.out.println(user + "??????????????????????????");
//        int r = userService.add(user);
//        //  int r = SpringUtil.getBean(UserService.class).add(user);
//        //return "forward:/showuser.jsp";
//
//        return "redirect:/addok.jsp";
//    }

    @PostMapping("add")
    @ResponseBody
    public Result add(@RequestBody User user) throws IOException {
        int r = userService.add(user);
        return r>0?Result.success():Result.error("增加失败");
    }
    @Autowired
    private RedisTemplate redisTemplate;
    @PostMapping("login")
    public Result login(String uname, String upass, HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println("登录验证在"+port+"服务器上");
        if (uname.startsWith("java83") && upass.equals("1234")) {
            //request.getSession().setAttribute("LOGIN_USER", uname);
            String key= UUID.randomUUID().toString();
            redisTemplate.opsForValue().set(key,uname,30, TimeUnit.MINUTES);
            return Result.success(key,"登录成功");
            //return Result.success(uname,"登录成功");
        }

        //response.setContentType("text/html;charest=utf-8");
        //response.getWriter().print("<script>alert('用户名或者密码错误');history.back();</script>");
        return Result.error("用户名或者密码错误");
    }

    //通过学员编号，获得学员的全部信息
    @GetMapping("get")
    public String get(long id, Model model) {
        User u = userService.get(id);
        model.addAttribute("user", u);
        return "user";
        //return "/WEB-INF/jsps/user.jsp";
        //return "/user.jsp";
    }

    @GetMapping("del-{id}")
    public String del(@PathVariable("id") long id){
        int r = this.userService.del(id);
        return "deluserok";
        //return "forward:ok.jsp";
    }
    @GetMapping("toUpdate-{id}")
    public String toUpdate(@PathVariable("id") long id,Model model){
        User user = this.userService.get(id);
        model.addAttribute("stu",user);
        return "updateUser";
    }
    @InitBinder// String----->Date
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
        // true:允许输入空值，false:不能为空值 }
        //特殊的格式
        //SimpleDateFormat d2 = new SimpleDateFormat("yyyy/MM/dd");

        //binder.registerCustomEditor(Date.class,"birthday", new CustomDateEditor(d2, true));

    }
}